﻿using DTcms.Common;
using DTcms.Web.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web.Mvc;

namespace DTcms.Web.Mvc.Areas.Admin.Controllers.Link
{
    public class LinkController : ManageController
    {
        protected int totalCount = 0;
        protected Model.manager managerModel = new Model.manager();
        protected string _action;
        protected int _id;
        protected int _site_id;
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            managerModel = GetAdminInfo();
            _action = DTRequest.GetQueryString("action");
            _id = DTRequest.GetQueryInt("id");
            _site_id = DTRequest.GetQueryInt("site_id");
            ViewBag.action = _action;
            ViewBag.id = _id;
            ViewBag.site_id = _site_id;
        }

        [ChkAdminScript("plugin_link", DTEnums.ActionEnum.View)]
        public ActionResult Link_List()
        {
            return View();
        }

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and title like '%" + _keywords + "%'");
            }
            return strTemp.ToString();
        }
        #endregion
        [ChkAdminJson("plugin_link", DTEnums.ActionEnum.View)]
        public JsonResult LinkList(string keywords, int _site_id=0, int page = 1, int limit = 10)
        {
            string strWhere = "id>0";
            if (_site_id > 0)
            {
                strWhere = " and site_id=" + _site_id;
            }
            strWhere += CombSqlTxt(keywords);
            string strOrder = "sort_id asc,add_time desc";
            BLL.plugin_link bll = new BLL.plugin_link();
            var resultList = bll.GetQueryPage(page, limit, strWhere, strOrder);
            DataTable Items = DataHelper.ListToDataTable(resultList.Items);
            DataTable oldData = Items.Clone();
            if (resultList.TotalItems > 0)
            {
                oldData.Columns.Add("siteTitle", Type.GetType("System.String"));
                foreach (DataRow item in Items.Rows)
                {
                    DataRow row = oldData.NewRow();
                    row["is_image"] = item["is_image"];
                    row["title"] = item["title"];
                    row["add_time"] = item["add_time"];
                    row["img_url"] = item["img_url"];
                    row["is_red"] = item["is_red"];
                    row["sort_id"] = item["sort_id"];
                    row["id"] = item["id"];
                    row["siteTitle"] = new BLL.sites().GetTitle(Utils.ObjToInt(item["site_id"]));
                    oldData.Rows.Add(row);
                }
            }
            return Json(new { status = 1, msg = "", item = oldData, totalCount = resultList.TotalItems });
        }

        [ChkAdminScript("plugin_link", DTEnums.ActionEnum.View)]
        public ActionResult Link_Edit()
        {
            Model.plugin_link model = new Model.plugin_link();
            BLL.plugin_link bll = new BLL.plugin_link();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = bll.Get(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
            }
            return View(model);
        }
        
        #region 审核
        [HttpPost]
        [ChkAdminScript("plugin_link", DTEnums.ActionEnum.Audit)]
        public JsonResult LinkAudit(List<int> ids)
        {
            BLL.plugin_link bll = new BLL.plugin_link();
            foreach (int id in ids)
            {
                bll.UpdateFile("id=" + id, "is_lock=0");
            }
            AddAdminLog(DTEnums.ActionEnum.Audit.ToString(), "审核友情链接"); //记录日志
            return Json(new { status = 1, msg = "批量审核成功！" });
        }
        #endregion

        #region 彻底删除
        [HttpPost]
        [ChkAdminScript("plugin_link", DTEnums.ActionEnum.Delete)]
        public JsonResult LinkDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.plugin_link bll = new BLL.plugin_link();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除友情链接成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }
        #endregion
        #region 个别字段修改
        [HttpPost]
        [ChkAdminScript("plugin_link", DTEnums.ActionEnum.Edit)]
        public JsonResult LinkFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.plugin_link bll = new BLL.plugin_link();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }
        #endregion

        #region 设置状态
        [HttpPost]
        [ChkAdminScript("plugin_link", DTEnums.ActionEnum.Edit)]
        public JsonResult LinkRed(int id, bool is_lock)
        {
            BLL.plugin_link bll = new BLL.plugin_link();
            if (bll.UpdateFile("id=" + id, "is_red=" + (is_lock ? 1 : 0)))
            {
                return Json(new { status = 1, msg = "设置状态成功！" });
            }
            return Json(new { status = 0, msg = "设置状态失败！" });
        }
        #endregion

        [HttpPost]
        public ActionResult LinkSave(Model.plugin_link t)
        {
            BLL.plugin_link bll = new BLL.plugin_link();
            t.sort_id = Utils.StrToInt(t.sort_id.ToString(), 99);
            t.is_red = DTRequest.GetFormString("is_red").Contains("true") ? 1 : 0;
            t.is_image = 1;
            if (string.IsNullOrEmpty(t.img_url))
            {
                t.is_image = 0;
            }
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("plugin_link", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.plugin_link model = bll.Get(_id);
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改友情链接:" + model.title); //记录日志
                }
                else
                {
                    return Json(new { status = 0, msg = "保存过程中发生错误！", url = "back" });
                }
                return Json(new { status = 1, msg = "修改链接成功！", url = "../link/link_list" });
            }
            else //添加
            {
                ChkAdminLevel("plugin_link", DTEnums.ActionEnum.Add.ToString()); //检查权限

                if (bll.Add(t) > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "添加友情链接:" + t.title); //记录日志
                }
                else
                {
                    return Json(new { status = 0, msg = "保存过程中发生错误！", url = "back" });
                }
                return Json(new { status = 1, msg = "添加链接成功！", url = "../link/link_list" });
            }
        }
    }
}
